import Vue from 'vue'
import Router from 'vue-router'
import Index from '../pages/index'
import Dashboard from './dashboard'
import routers from './routers'
import baiduRouters from './baiduRouter'
import kwaiRouters from './kwaiRouter'
import douJiaRouter from './douJiaRouter'
import { mscf } from '@/util'

Vue.use(Router)
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push(to) {
  if (process.env.NODE_ENV === 'development') return VueRouterPush.call(this, to)
  if (!to.name) {
    let path = to.path ? to.path : to
    path = path.endsWith('?') ? path.substr(0, path.length - 1) : path
    let routes = this.options.routes[0].children
    let newTo = routes.filter((item) => item.path === path || item.path.indexOf(`${path}/:`) !== -1)[0]
    to = to.path
      ? {
          ...to,
          name: newTo.name
        }
      : {
          path,
          name: newTo.name
        }
  }
  return mscf.emit('redirect', '*', {
    target: mscf.name,
    page: to.name,
    query: {
      breadCrumbs: this.history.current.path,
      ...to.query,
      _r: (Math.random() * 100).toFixed(0)
    },
    params: {
      ...to.params
    }
  })
}

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      redirect: '/dashboard',
      component: Index,
      children: [...Dashboard.routes, ...routers, ...baiduRouters, ...kwaiRouters, ...douJiaRouter]
    },
    { path: '*', redirect: '/' }
  ]
})

router.beforeEach((to, from, next) => {
  mscf.emit('routeChange', '*', to.fullPath)
  next()
})
export default router
